package com.lianxd.easybuy.servlet;

import cn.hutool.core.util.StrUtil;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
  @Override
  public  void service(ServletRequest req, ServletResponse res)throws ServletException, IOException{
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html:charset=utf-8");
    String name = request.getParameter("action");
    if (StrUtil.isNotEmpty(name)){
      //action参数值一定要规范
      System.out.println("name = "+ name);
      Class clazz = this.getClass();
      Method method = null;
      try {
        method = clazz.getDeclaredMethod(name,HttpServletRequest.class,HttpServletResponse.class);
        method.setAccessible(true);
        method.invoke(this,request,response);
      } catch (NoSuchMethodException e) {
        response.sendError(500,"没有查找到"+ name + "方法,请检查");
      } catch (IllegalAccessException e) {
        response.sendError(500,"您没有访问"+ name +"方法的权限");
      } catch (InvocationTargetException e) {
        response.sendError(500,"您调用的"+ name +"方法的内部抛出错误,错误信息:"+e.getMessage());
      }
    }else {
      response.sendError(500,"action参数为null,请您检查参数");
    }

  }
}
